<script setup>
import {Role} from '@/utils/resource'
import {showSaveResponse} from '@/utils/element-helper'
import {useRouter} from "vue-router";
import {ref, nextTick, reactive} from "vue";

const props = defineProps({
  username: {
    type: String,
    default: ""
  }
})
const username = props.username
const router = useRouter()
const loading = ref(false)
const state = reactive({
  data: [],
  choosed: []
})

loading.value = true
Promise.all([loadRoles(), loadUserRoles()]).then(() => {
  nextTick(() => {
    loading.value = false
  })
})


async function loadRoles() {
  let res = await Role.list()
  let roles = []
  for (let i = 0; i < res.data.length; i++) {
    let role = res.data[i]
    roles.push({
      key: role.id,
      label: role.name
    })
  }
  state.data = roles
}

async function loadUserRoles() {
  let res = await Role.userRole(username)
  state.choosed = res.data.map(d => d.id)
}

async function save() {
  showSaveResponse(loading.value, () => saveUserRole(), router.back())
}

async function saveUserRole() {
  return Role.saveUserRole(username, state.choosed)
}
</script>

<template>
  <div>
    <div style="padding-left: 20px;text-align: center" v-loading="loading">
      <el-transfer v-model="state.choosed" :data="state.data" style="text-align: left; display: inline-block"
                   :titles="['未选角色', '已选角色']"
                   :button-texts="['移除角色', '添加角色']">
      </el-transfer>
    </div>
    <div style="padding: 15px">
      <router-link to="/user">
        <el-button plain round type="info" icon="Back" style="margin-right: 10px;">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="save" icon="CircleCheck">保存</el-button>
    </div>
  </div>
</template>


<style scoped>

</style>
